import React from 'react';
import { SearchOutlined, UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Input, Select, message, Upload, Spin, Modal, AutoComplete } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import { requestHeadersMd5 } from '@/utils/utils';
import HOCSelect from '@/components/AntDesign/Select';
import DictCode from '../../components/DictCode';

const { Option } = Select;
const FormItem = Form.Item;
const { confirm } = Modal;
const { TextArea } = Input; // 文本域
// const { Search } = Input;

@connect(({ issueprove, loading }) => ({
  issueprove,
  loading: loading.effects['issueprove/fetchEmpNameList'],
  submitLoading: loading.effects['issueprove/featchCheckIssueProveAdd'] || loading.effects['issueprove/featchIssueProveUpdate'],
}))
class issureproofadd extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const { location } = this.props;
    const { id } = location.query;

    if (id) {
      this.detail(id);
    } else {
      this.resetProps(); // 解决切换左边菜单props未清空的bug
    }
  }

  componentWillUnmount() {
    this.resetProps();
  }

  // 解决切换左边菜单props未清空的bug
  resetProps = () => {
    const { dispatch } = this.props;
    const opermars = {
      updateDetail: {
        hdlWay: undefined,
        hdlFlag: '1',
        state: '1',
      },
      fileListEmlOld: [],
      fileListExprsOld: [],
      fileListHandOld: [],
      proveSerHdlId: undefined,
    };

    dispatch({
      type: 'issueprove/updateModelData',
      payload: opermars,
    });
  };

  detail = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'issueprove/fetchUpdateDetail',
      payload: { proveSerHdlId: id },
    });
  };

  // 办理方式
  handleTypeChange = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'issueprove/changeDomShow',
      payload: value,
    });
  };

  // 本人--待办
  commissionChange = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'issueprove/changeChildDomShow',
      payload: e.target.value,
    });
  };

  // 取消
  submitcancel = () => {
    confirm({
      title: '提示',
      content: '确定要离开页面吗?',
      okText: '离开',
      cancelText: '取消',
      onOk() {
        router.push('/hrmanage/issueproof/index');
      },
      onCancel() {},
    });
  };

  // 搜索人
  search = value => {
    const { dispatch } = this.props;
    if (value.trim().length) {
      const values = {
        empName: value.trim(),
      };
      dispatch({
        type: 'issueprove/fetchEmpNameList',
        payload: values,
      });
    }
  };

  // 选择人员
  empData = value => {
    const {
      issueprove: { empNameList },
    } = this.props;
    if (empNameList) {
      empNameList.map(item => {
        if (item.sendId === value) {
          this.valueBase(item);
        }
        return true;
      });
    }
  };

  // 选择身份证号
  valueBase = item => {
    const { form, dispatch } = this.props;
    this.setState({
      empName: item.empName,
    });
    Object.keys(item).forEach(key => {
      if (
        key === 'areaId' ||
        key === 'custId' ||
        key === 'empId' ||
        key === 'certNo' ||
        key === 'certType' ||
        key === 'contactEmail'
      ) {
        this.setState({
          [key]: item[key],
        });
      }
    });
    form.resetFields();
    form.setFieldsValue({
      empName: item.empName,
      certNo: item.certNo,
      custName: item.custName,
      areaName: item.areaName,
      entryStatusName: item.entryStatusName,
    });
    dispatch({
      type: 'issueprove/updateModelEmail',
      payload: { updateDetail: { recEml: item.contactEmail } },
    });
  };

  // 搜索证件号
  searchCert = () => {
    const { form, dispatch } = this.props;
    form.validateFieldsAndScroll(['certNo'], (err, values) => {
      if (!err) {
        if (values) {
          dispatch({
            type: 'issueprove/fetchEmpNameList',
            payload: values,
          }).then(resp => {
            if (resp.success) {
              if (resp.data && resp.data.length === 0) {
                message.warning('当前所输的证件号不存在，请检查 ');
                form.resetFields(['empName', 'custName', 'areaName', 'entryStatusName']);
              } else {
                const certObj = resp.data[0];
                this.valueBase(certObj);
              }
            } else {
              message.warning(resp.message || '服务器错误');
            }
          });
        }
      }
    });
  };

  // 表单检测 并 提交
  submitAll = () => {
    const { form, dispatch, issueprove } = this.props;
    const { updateDetail } = issueprove;
    form.validateFieldsAndScroll({ force: true }, (err, fieldsValue) => {
      if (err) return;
      const { areaId, custId, empId, empName, certType } = this.state;
      const values = fieldsValue;
      let fileEmlName = '';
      let fileHandName = '';
      let fileExprsName = '';
      values.empName = empName;
      values.custId = custId;
      values.certType = certType;
      if (String(updateDetail.hdlWay) === '1') {
        if (issueprove.fileListEmlOld && issueprove.fileListEmlOld.length) {
          issueprove.fileListEmlOld.forEach(item => {
            if (item.response && item.response.success) {
              fileEmlName += item.response.data.concat(',');
            } else if (!item.responss) {
              fileEmlName += item.uid
                .concat('|')
                .concat(item.name)
                .concat(',');
            }
          });
        }
        values.emlAffix = fileEmlName ? fileEmlName.slice(0, fileEmlName.length - 1) : null;
      }
      if (String(updateDetail.hdlWay) === '2') {
        if (issueprove.fileListHandOld && issueprove.fileListHandOld.length) {
          issueprove.fileListHandOld.forEach(item => {
            if (item.response && item.response.success) {
              fileHandName += item.response.data.concat(',');
            } else if (!item.responss) {
              fileHandName += item.uid
                .concat('|')
                .concat(item.name)
                .concat(',');
            }
          });
        }
        values.affix = fileHandName ? fileHandName.slice(0, fileHandName.length - 1) : null;
      }
      if (String(updateDetail.hdlWay) === '3') {
        if (issueprove.fileListExprsOld && issueprove.fileListExprsOld.length) {
          issueprove.fileListExprsOld.forEach(item => {
            if (item.response && item.response.success) {
              fileExprsName += item.response.data.concat(',');
            } else if (!item.responss) {
              fileExprsName += item.uid
                .concat('|')
                .concat(item.name)
                .concat(',');
            }
          });
        }
        values.exprsAffix = fileExprsName ? fileExprsName.slice(0, fileExprsName.length - 1) : null;
      }
      if (updateDetail.proveSerHdlId) {
        dispatch({
          type: 'issueprove/featchIssueProveUpdate',
          payload: { ...values, proveSerHdlId: updateDetail.proveSerHdlId, vno: updateDetail.vno },
        });
      } else {
        dispatch({
          type: 'issueprove/featchCheckIssueProveAdd',
          payload: { ...values, areaId, empId, custId },
        }).then(response => {
          if (response.data.code === '201') {
            message.error('该姓名已存在，不可以新增！');
          } else if (response.data.code === '202') {
            confirm({
              title: '提醒',
              content: '当前人员已存在此项服务，是否确定重复添加?',
              okText: '确定',
              okType: 'danger',
              cancelText: '取消',
              onOk: () => {
                dispatch({
                  type: 'issueprove/featchIssueProveAdd',
                  payload: { ...values, areaId, custId, empId },
                });
              },
              onCancel() {},
            });
          } else if (response.data.code === '200') {
            router.goBack();
          }
        });
      }
    });
  };

  render() {
    const { form, issueprove, loading, submitLoading, dispatch } = this.props;
    const { updateDetail } = issueprove;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 8,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 10,
        },
      },
    };

    const propsExprs = {
      name: 'file',
      action: '/esApi/fileServer/uploadFile',
      headers: {
        authorization: 'authorization-text',
        ...requestHeadersMd5(),
      },
      onChange: ({ file }) => {
        if (file.status === 'done' && file.response.success) {
          message.success(file.response.message);
        } else if (file.status === 'error') {
          message.error(`文件上传失败！`);
        }
      },
      onRemove: file => {
        dispatch({
          type: 'issueprove/updateExprsDele',
          payload: file,
        });
      },
      fileList: issueprove.fileListExprsOld,
      beforeUpload: (file, fileList) => {
        dispatch({
          type: 'issueprove/updateExprsData',
          payload: fileList,
        });
      },
    };
    const propsEml = {
      name: 'file',
      action: '/esApi/fileServer/uploadFile',
      headers: {
        authorization: 'authorization-text',
        ...requestHeadersMd5(),
      },
      onChange: ({ file }) => {
        if (file.status === 'done' && file.response.success) {
          message.success(file.response.message);
        } else if (file.status === 'error') {
          message.error(`文件上传失败！`);
        }
      },
      onRemove: file => {
        dispatch({
          type: 'issueprove/updateEmlDele',
          payload: file,
        });
      },
      fileList: issueprove.fileListEmlOld,
      beforeUpload: (file, fileList) => {
        dispatch({
          type: 'issueprove/updateEmlData',
          payload: fileList,
        });
      },
    };
    let options = null;
    if (issueprove.empNameList && issueprove.empNameList.length) {
      options = issueprove.empNameList.map(opt => (
        <Option key={opt.sendId}>{`${opt.certNo} (${opt.custName})`}</Option>
      ));
    }

    const propsHandle = {
      name: 'file',
      action: '/esApi/fileServer/uploadFile',
      headers: {
        authorization: 'authorization-text',
        ...requestHeadersMd5(),
      },
      onChange: ({ file }) => {
        if (file.status === 'done' && file.response.success) {
          message.success(file.response.message);
        } else if (file.status === 'error') {
          message.error(`文件上传失败！`);
        }
      },
      onRemove: file => {
        dispatch({
          type: 'issueprove/updateHandDele',
          payload: file,
        });
      },
      fileList: issueprove.fileListHandOld,
      beforeUpload: (file, fileList) => {
        dispatch({
          type: 'issueprove/updateHandData',
          payload: fileList,
        });
      },
    };

    return (
      <PageHeaderWrapper>
        <Card title={<span>{issueprove.rcrdId ? '修改' : '开证明'}</span>}>
          <Form>
            <FormItem {...formItemLayout} label={<span>姓名 </span>}>
              {getFieldDecorator('empName', {
                rules: [
                  {
                    required: true,
                    message: '只能输入汉字或者英文',
                  },
                ],
                initialValue: updateDetail.empName || undefined,
              })(
                <HOCSelect
                  placeholder="请输入关键字检索"
                  style={{ width: '100%' }}
                  showSearch
                  optionFilterProp="children"
                  showArrow={false}
                  onSearch={this.search}
                  onSelect={this.empData}
                  notFoundContent={loading ? <Spin size="small" /> : '暂无数据'}
                >
                  {issueprove.empNameList.length &&
                    issueprove.empNameList.map(item => (
                      <Option key={item.sendId}>{`${item.empName}(${item.custName})`}</Option>
                    ))}
                </HOCSelect>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="证件号:">
              {getFieldDecorator('certNo', {
                rules: [
                  {
                    required: true,
                    message: '请输入证件号',
                  },
                ],
                initialValue: updateDetail.certNo || undefined,
              })(
                // <Search placeholder="请输入证件号" onSearch={this.idVailFunc} />
                <AutoComplete
                  dropdownMatchSelectWidth={false}
                  // style={{ width: '96%' }}
                  dataSource={options}
                  placeholder="请输入证件号"
                  onSelect={this.empData}
                >
                  <Input suffix={<SearchOutlined onClick={this.searchCert} />} />
                </AutoComplete>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={<span>客户名称</span>}>
              {getFieldDecorator('custName', {
                rules: [
                  {
                    required: true,
                    message: '请填写客户名称',
                  },
                ],
                initialValue: updateDetail.custName || undefined,
              })(<Input placeholder="请填写客户名称" disabled />)}
            </FormItem>
            <FormItem {...formItemLayout} label={<span>执行地</span>}>
              {getFieldDecorator('areaName', {
                rules: [
                  {
                    required: true,
                    message: '请填写执行地',
                  },
                ],
                initialValue: updateDetail.areaName || undefined,
              })(<Input placeholder="请填写执行地" disabled />)}
            </FormItem>
            <FormItem {...formItemLayout} label={<span>在职状态</span>}>
              {getFieldDecorator('entryStatusName', {
                rules: [
                  {
                    required: true,
                    message: '请填写在职状态',
                  },
                ],
                initialValue: updateDetail.entryStatusName || undefined,
              })(<Input placeholder="请填写在职状态" disabled />)}
            </FormItem>
            <FormItem {...formItemLayout} label="证明类型">
              {getFieldDecorator('proveType', {
                rules: [
                  {
                    required: true,
                    message: '请填写证明类型',
                  },
                ],
                initialValue: updateDetail.proveType && `${updateDetail.proveType}`,
              })(<DictCode dictType="PROVE_TYPE" />)}
            </FormItem>
            <FormItem {...formItemLayout} label={<span>任务来源</span>}>
              {getFieldDecorator('tskSource', {
                rules: [
                  {
                    required: true,
                    message: '请选择任务来源',
                  },
                ],
                initialValue: updateDetail.tskSource && `${updateDetail.tskSource}`,
              })(<DictCode dictType="TSK_SOURCE" />)}
            </FormItem>
            <FormItem {...formItemLayout} label={<span>办理方式</span>}>
              {getFieldDecorator('hdlWay', {
                rules: [
                  {
                    required: true,
                    message: '请选择办理方式',
                  },
                ],
                initialValue: updateDetail.hdlWay && `${updateDetail.hdlWay}`,
              })(<DictCode dictType="HANDLE_WAY" onChange={this.handleTypeChange} />)}
            </FormItem>

            {/* 邮件 */}
            {String(updateDetail.hdlWay) === '1' && (
              <div>
                <FormItem {...formItemLayout} label={<span>收件人邮箱</span>}>
                  {getFieldDecorator('recEml', {
                    rules: [
                      {
                        type: 'email',
                        message: '请输入邮箱格式!',
                      },
                      {
                        required: String(updateDetail.hdlWay) === '1' && true,
                        message: '请填写收件人邮箱',
                      },
                    ],
                    initialValue: updateDetail.recEml,
                  })(<Input placeholder="请输入发送人邮箱" />)}
                </FormItem>

                <FormItem {...formItemLayout} label={<span>附件</span>}>
                  {getFieldDecorator('emailAffix', {
                    rules: [
                      {
                        required: false,
                        message: '请填写邮件',
                      },
                    ],
                  })(
                    <Upload {...propsEml}>
                      <Button>
                        <UploadOutlined /> 上传附件
                      </Button>
                    </Upload>
                  )}
                </FormItem>
              </div>
            )}

            {/* 快递单号 */}
            {String(updateDetail.hdlWay) === '3' && (
              <div>
                <FormItem {...formItemLayout} label={<span>邮寄地址</span>}>
                  {getFieldDecorator('exprsAddr', {
                    rules: [
                      {
                        required: String(updateDetail.hdlWay) === '3' && true,
                        message: '邮寄地址长度不能超过100位',
                        max: 100,
                      },
                    ],
                    initialValue: updateDetail.exprsAddr || undefined,
                  })(<Input placeholder="请输入邮寄地址" />)}
                </FormItem>
                <FormItem {...formItemLayout} label={<span>快递单号</span>}>
                  {getFieldDecorator('exprsNo', {
                    rules: [
                      {
                        required: String(updateDetail.hdlWay) === '3' && true,
                        message: '快递单号长度不能超过20位',
                        max: 20,
                      },
                    ],
                    initialValue: updateDetail.exprsNo || undefined,
                  })(<Input placeholder="请输入快递单号" />)}
                </FormItem>
                <FormItem {...formItemLayout} label={<span>快递公司</span>}>
                  {getFieldDecorator('exprsCorpName', {
                    rules: [
                      {
                        required: String(updateDetail.hdlWay) === '3' && true,
                        message: '快递公司长度不能超过30位',
                        max: 30,
                      },
                    ],
                    initialValue: updateDetail.exprsCorpName || undefined,
                  })(<Input placeholder="请输入快递公司" />)}
                </FormItem>
                <FormItem {...formItemLayout} label={<span>附件</span>}>
                  {getFieldDecorator('exprsAffix', {
                    rules: [
                      {
                        required: false,
                        message: '请上传附件',
                      },
                    ],
                  })(
                    <Upload {...propsExprs}>
                      <Button>
                        <UploadOutlined /> 上传附件
                      </Button>
                    </Upload>
                  )}
                </FormItem>
              </div>
            )}
            {/* 现场 */}
            {String(updateDetail.hdlWay) === '2' && (
              <div>
                <FormItem {...formItemLayout} label={<span>本人/代办</span>}>
                  {getFieldDecorator('hdlFlag', {
                    rules: [
                      {
                        required: String(updateDetail.hdlWay) === '2' && true,
                        message: '请填写代办人姓名',
                      },
                    ],
                    initialValue: (updateDetail.hdlFlag && `${updateDetail.hdlFlag}`) || '1',
                  })(
                    <DictCode
                      dictType="SELF_HANDLE_FLAG"
                      inputType="3"
                      onChange={this.commissionChange}
                    />
                  )}
                </FormItem>
                {/* 待办 */}
                {String(updateDetail.hdlFlag) === '2' && (
                  <div>
                    <FormItem {...formItemLayout} label={<span>代办人姓名</span>}>
                      {getFieldDecorator('hdlName', {
                        rules: [
                          {
                            required: String(updateDetail.hdlFlag) === '2' && true,
                            message: '请填写代办人姓名',
                          },
                        ],
                        initialValue: updateDetail.hdlName || undefined,
                      })(<Input placeholder="代办人姓名" />)}
                    </FormItem>
                    <FormItem {...formItemLayout} label={<span>代办人证件类型</span>}>
                      {getFieldDecorator('hdlCertType', {
                        rules: [
                          {
                            required: String(updateDetail.hdlFlag) === '2' && true,
                            message: '请选择代办人证件类型',
                          },
                        ],
                        initialValue: updateDetail.hdlCertType && `${updateDetail.hdlCertType}`,
                      })(<DictCode dictType="ADD_ID_TYPE" />)}
                    </FormItem>

                    <FormItem {...formItemLayout} label={<span>代办人证件号</span>}>
                      {getFieldDecorator('hdlCertNo', {
                        rules: [
                          {
                            required: String(updateDetail.hdlFlag) === '2' && true,
                            message: '请填写代办人证件号',
                          },
                        ],
                        initialValue: updateDetail.hdlCertNo || undefined,
                      })(<Input placeholder="请输入代办人证件号" />)}
                    </FormItem>
                  </div>
                )}
              </div>
            )}
            {String(updateDetail.hdlWay) === '2' && (
              <div>
                <FormItem {...formItemLayout} label={<span>附件</span>}>
                  {getFieldDecorator('handleAffix', {
                    rules: [
                      {
                        required: false,
                        message: '请填写邮件',
                      },
                    ],
                  })(
                    <Upload {...propsHandle}>
                      <Button>
                        <UploadOutlined /> 上传附件
                      </Button>
                    </Upload>
                  )}
                </FormItem>
              </div>
            )}
            <FormItem {...formItemLayout} label="备注">
              {getFieldDecorator('remark', {
                rules: [
                  {
                    required: false,
                    max: 300,
                    message: '请输入不得超过300字的备注',
                  },
                ],
                initialValue: updateDetail.remark || undefined,
              })(<TextArea placeholder="请输入备注" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="状态">
              {getFieldDecorator('state', {
                rules: [
                  {
                    required: true,
                  },
                ],
                initialValue: `${updateDetail.state}`,
              })(<DictCode dictType="PROVE_STATUS" inputType="3" />)}
            </FormItem>
          </Form>
        </Card>
        <FooterToolbar>
          <Button onClick={this.submitcancel}>取消</Button>
          <Button type="primary" onClick={this.submitAll} loading={submitLoading}>
            提交
          </Button>
        </FooterToolbar>
      </PageHeaderWrapper>
    );
  }
}

const issureproofaddform = Form.create()(issureproofadd);
export default issureproofaddform;
